<?php

namespace app\admin\service;

use app\admin\model\Admin;
use app\admin\model\Member as MemberMdl;
use app\admin\model\Memberlevel;
use app\admin\model\Membercoupon;
use app\admin\model\Store;

use think\Db;
use think\Exception;

class Member
{

    /**
     * 导出数据
     */
    public static function export($request){
        $param = $request->param();

        $where = [
            'm_status' => 1,
        ];

        $model = new MemberMdl();
        $data = $model->where($where)->select();
        if(count($data) <= 0){
            return [
                'code' => 2,
                'msg' => '没有数据！'
            ];
        }

        foreach ($data as $key => $item) {

            // 是否为党员
            switch ($item['sex']) {
                case 1: $item['sex'] = '男'; break;
                case 2: $item['sex'] = '女'; break;
                default : $item['sex'] = '男'; break;
            }
            $item['member_level'] = Memberlevel::where('id',  $item['member_level_id'])->value('name');
            // 优惠券
            $item['count_coupon'] = Membercoupon::where(['member_id' => $item['id']])->count();
            if($item['balance']){
                $item['balance'] = $item['balance'] / 100;
            }
            if ($item['open_store_id'] && $item['open_store_type'] != 1) {
                // 开通门店
                $item['open_store'] = Store::where(['id' => $item['open_store_id']])->value('name');
                // 开通人
                $item['open_person'] = Admin::where(['id' => $item['open_person']])->value('name');
            } else {
                $item['open_store'] = '';
                $item['open_person'] = '';
            }
        }

        $cellName = array(
            'A' => ['account_number', '会员账号'],
            'B' => ['name', '真实姓名'],
            'C' => ['sex', '性别'],
            'D' => ['birthday', '生日'],
            'E' => ['member_level', '会员等级'],
            'F' => ['balance', '余额'],
            'G' => ['integral', '积分'],
            'H' => ['count_coupon', '优惠券'],
            'I' => ['open_store', '开通门店'],
            'J' => ['open_person', '开通人'],
            'K' => ['open_time', '开通时间'],
            'L' => ['end_time', '到期时间'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'member' . DS . date('Y-m-d');
        $fileName = $filePath . '/member_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel::exportExcel('会员', $data, $cellName, $filePath, $fileName);

        return [
            'code' => 1,
            'msg' => '导出成功！'
        ];
    }

}